import {observable, action} from 'mobx';
import { ListStore } from './listStore'
import { WeaTools } from 'ecCom';
import * as API_LIST from '../apis/implementation'
import * as API_HIS from '../apis/rptHistory'
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import {message} from 'antd';
import {WeaTableNew} from 'comsMobx'
const {TableStore} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

/**
 * 预算执行情况表的Store
 */
export class ImplementationStore extends ListStore{

	//高级搜索默认值
	@observable baseParams = {

    };
	//tab默认值
	@observable searchParams = {
        index:0
    };

    //GUID
    guid='';

    //保存模型的数据
    modalSaveParam={
    	tbName:''
    };

    //保存报表的Modal的显隐
    @observable showModal = false;

    //是否显示保存查询结果按钮
    @observable saveFlag = false;

    //是否点击了高级查询
    @observable isSearch = false;

    //保存历史高级搜索的查询参数
    advHisSearchParam = {
        nameQuery:""
    };

	constructor(){
		super();
		this.title = "";
        this.pageType = 'BudgetPerformanceStatement';
        this.showShareModel = false;
		this.appendBaseParams = this.appendBaseParams.bind(this);
		this.initDatas = this.initDatas.bind(this);
		this.doSearch = this.doSearch.bind(this);
		this.initInfo = this.initInfo.bind(this);
		this.baseHisSearch = this.baseHisSearch.bind(this);
		this.setShowModal = this.setShowModal.bind(this);
		this.saveTempData = this.saveTempData.bind(this);
		this.historyDelete = this.historyDelete.bind(this);
		this.generGUID = this.generGUID.bind(this);
		this.saveModelInfo = this.saveModelInfo.bind(this);
		this.setModalSaveParam = this.setModalSaveParam.bind(this);
		this.setSaveFlag = this.setSaveFlag.bind(this);
		this.setIsSearch = this.setIsSearch.bind(this);
		this.saveGUID = this.saveGUID.bind(this);
	}

	@action
    appendBaseParams(params) {
        this.baseParams = {...this.baseParams,...params};
    }

	
	initDatas(params = {}){
		this.initInfo("init");
		let value = Object.assign({},{
				qryFunctionType:0,
				rptViewType:0
			});
		this.doSearch(value);
	}

	//初始化高级搜索
	initInfo(value,params = {}){
		API_LIST.implementationInfoP(params).then(data =>{
            if(data.flag == 'success'){
                this.hasRight = 1;

                const { conditions } = data;
    			this.condition = conditions;
                this.form = new WeaForm();
    			this.form.initFormFields(conditions);
                if(value=="init"){
                    //初始化tab列表  
                    let tabTitle = [{title:getLabel(24616,'查询报表'),key:0},{title:getLabel(82503,'历史查询结果'),key:1}];
                    this.topTab = tabTitle;
                    this.topTabCount = 2;
                    this.setShowSearchAd(true);
                } else if(value.flag){             
                    this.hisAdvViewBack(value);
                }
            } else {
                this.hasRight = 4;
            }

		});		
	}

	//保存临时数据
	saveTempData(params = {},callback){
		const searchParamsAd = this.form.getFormParams();
		const newParams = { ...this.baseParams, ...searchParamsAd, ...params };
        this.loading = true; 
		API_LIST.saveImplementationTempData(newParams).then(data =>{
            let result = JSON.parse(data.resultJson)
            if(result.flag){
                callback && callback();
            } else {
                message.error(result.msg);
                this.isSearch = false;
            }
		});
	}

	//TABLE数据
	doSearch(params = {},flag = true,callback) {
		if(this.searchParams.index==0){
            const searchParamsAd = this.form.getFormParams();
            const newParams = { ...this.baseParams, ...searchParamsAd, ...params };
			this.loading = true; 
			API_LIST.implementationReportP(newParams).then(data =>{
    			if(data.flag == 'success'){
                    this.hasRight = 1;
                    this.tableStore = new TableStore();
                    if(flag){//回到第一页
                        this.tableStore.getDatas(data.datas,1);
                    }else{
                        this.tableStore.getDatas(data.datas);
                    }
                    this.dataKey = data.datas;
                    callback && callback();
                } else {
                    this.hasRight = 4;
                }  
                this.loading = false;           
			});
		}else{
            const searchParamsAd = this.formHis.getFormParams();
			let nameQuery = searchParamsAd.advQryName;
			const value = Object.assign({},searchParamsAd,{
	    		nameQuery:typeof(nameQuery)=='undefined'?'':nameQuery,
	    		rptTypeName:'fnaRptImplementation'
    		});
            this.advHisSearchParam = value;
			this.queryHistoryData(value);
		}
	}

	//基础搜索
    baseHisSearch(params = {}){
    	// this.form.updateFields({
    	// 	advQryName:{value:params.nameQuery}
    	// },updateAll = false);
    	this.queryHistoryData(params);
    }

    //历史记录删除
    historyDelete(params){
    	API_HIS.historyDelete(params).then(data=>{
            if(data.flag == 'success'){
                this.hasRight = 1;
                this.queryHistoryData({rptTypeName:'fnaRptImplementation'},false);//解决异步问题
            }else{
                this.hasRight = 4;
            }
    	});
    }

    //生成GUID
    generGUID(func){
    	API_HIS.getGUIDP().then(data=>{
            this.guid=data.guid;
            func && func();//外部的回调,防止程序速度，快与XHR
    	});
    }

    //保存GUID
    saveGUID(value){
        this.guid=value;
    }

    //在查询中打开高级搜索数据回显
    hisAdvViewBack = (params) =>{
        let obj = [];
        let subobj = [];
        let param = [];
        let subparam = [];
        let ids = [];
        let names = [];
        if(typeof(params.orgId)!="undefined" && params.orgId!=""){
            ids = params.orgId.split(',');
            names = params.orgIdName.split(',');
            for(let index=0;index<ids.length;index++){
            obj.push({id:ids[index],name:names[index]});
            }
        }
        param=[params.orgId,params.orgIdName,obj];

        if(typeof(params.subjectId)!="undefined" && params.subjectId!=""){
            ids = params.subjectId.split(',');
            names = params.subjectName.split(',');
            for(let index=0;index<ids.length;index++){
            subobj.push({id:ids[index],name:names[index]});
            }
        }
        subparam = [params.subjectId,params.subjectName,subobj];
        // console.log(" params.subjectType",  params.subjectType);
        this.form.updateFields({
            orgType__orgId:{
                value:[
                params.orgType+'',
                param
                ],
                valueSpan:['orgId']
            },
            subjectType__subjectIds:{
                value:[
                params.subjectType,
                subparam
                ],
                valueSpan:['subjectIds']
            },
            sumSubOrg:{
                value: params.sumSubOrg
            },
            fnayear:{
                value:params.fnayear
            },
            fnayearperiod:{
                value:params.fnayearperiod
            }
            });

            //回显的Bug修复
            const {subjectType} = params;
            if(subjectType == '1'){
                this.form.updateFields({
                    monthPeriod:{
                        value:params.fnayearperiod,
                        valueObj:params.fnayearperiod.split(',')
                    }
                });
            } else if(subjectType == '2'){
                this.form.updateFields({
                    quarterPeriod:{
                        value:params.fnayearperiod,
                        valueObj:params.fnayearperiod.split(',')
                    }
                });
            } else if(subjectType == '3'){
                this.form.updateFields({
                    halfYearPeriod:{
                        value:params.fnayearperiod,
                        valueObj:params.fnayearperiod.split(',')
                    }
                });
            } else if(subjectType == '4'){
                this.form.updateFields({
                    allYearPeriod:{
                        value:params.fnayearperiod,
                        valueObj:params.fnayearperiod.split(',')
                    }
                });
            }
    }

    //保存momal的显隐
    @action
    setShowModal(bool){
    	this.showModal=bool;
    }

    //保存报表
    saveModelInfo(params){
        this.loading = true;
    	API_HIS.saveReportP(params).then(data=>{
    		if(data.flag == 'success'){
                this.hasRight = 1;
                if(this.searchParams.index=='1'){
        			this.baseHisSearch({rptTypeName:'fnaRptImplementation'});//刷新
        		}
            }else{
                this.hasRight = 4;
            }
            this.loading = false;
    	});
    	//保存状态
    	this.saveFlag=true;
    }

    //保存momal的数据
    setModalSaveParam(params){
    	this.modalSaveParam={...this.modalSaveParam,...params};
    }

    //是否显示保存查询结果按钮
    @action 
    setSaveFlag(bool){
    	this.saveFlag = bool;
    }

    //是否点击了高级搜索
    @action 
    setIsSearch(bool){
    	this.isSearch = bool;
    }


    //设置历史高级搜索的查询参数
    setAdvHisSearchParam = (value) => {
        this.advHisSearchParam = value;
    }

    //数据重置，防止存留数据导致的页面显示不正常
    resetData = () => {
        this.tabKey = 0;

        this.showShareModel = false;

        //高级搜索默认值
        this.baseParams = {

        };
        //tab默认值
        this.searchParams = {
            index:0
        };

        //GUID
        this.guid='';

        //保存模型的数据
        this.modalSaveParam={
            tbName:''
        };

        //保存报表的Modal的显隐
        this.showModal = false;

        //是否显示保存查询结果按钮
        this.saveFlag = false;

        //是否点击了高级查询
        this.isSearch = false;

        //保存历史高级搜索的查询参数
        this.advHisSearchParam = {
            nameQuery:""
        };
    }
}